/****************
 * Lukasz Kufel *
 ****************/

import std.stdio;
import std.string;

import derelict.opengl.gl;
import derelict.sdl.sdl;
import derelict.opengl.glu;

import Cube;

const WINDOW_WIDTH		= 800;
const WINDOW_HEIGHT		= 600;
const BITS_PER_PIXEL	= 24;

const float FOV			= 90f;
const float NEAR_PLANE	= .1f;
const float FAR_PLANE	= 100.f;

Cube[] cubes;
bool exit = false;
GLfloat xRotate = 0.1;
GLfloat yRotate = 0.1;
GLfloat zRotate = 0.1;

void main(){
	init();
	scope(exit) cleanup();
	initShapes();
	
	//mainLoop:
	while (!exit) {
		
		eventHandler();
		
		glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
		glLoadIdentity();
		drawGLFrame();
		SDL_GL_SwapBuffers();
	}
}

void cleanup() {
	SDL_Quit();
	DerelictGLU.unload();
	DerelictGL.unload();
	DerelictSDL.unload();
}

void init(){
	DerelictSDL.load();
	DerelictGL.load();
	DerelictGLU.load();
	
	SDL_Init(SDL_INIT_VIDEO | SDL_INIT_TIMER);
	SDL_GL_SetAttribute(SDL_GL_DOUBLEBUFFER, 1);
	SDL_SetVideoMode(WINDOW_WIDTH, WINDOW_HEIGHT, BITS_PER_PIXEL, SDL_OPENGL);
	SDL_WM_SetCaption(toStringz("DerelictGL"), null);
	
	glEnable(GL_DEPTH_TEST);
	
	glHint(GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST);
	
	//glEnable(GL_LIGHTING);
	//glEnable(GL_NORMALIZE);
	//glShadeModel(GL_SMOOTH);
	glEnable(GL_COLOR_MATERIAL);
	glClearColor(0.3f, 0.3f, 0.3f, 1.0f);  // ustawienia tla sceny
	setupGL();
}

void setupGL() {
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(FOV, cast(float)WINDOW_WIDTH / WINDOW_HEIGHT, NEAR_PLANE, FAR_PLANE);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

void initShapes(){
	cubes ~= new Cube;
}

void eventHandler(){
	SDL_Event event;
		while (SDL_PollEvent(&event)) {
			switch (event.type) {
				case SDL_KEYUP:
					if (event.key.keysym.sym == SDLK_ESCAPE) {
						exit = true;
					} /*else if (event.key.keysym.sym == SDLK_ESCAPE){
						
					} else if (event.key.keysym.sym == SDLK_ESCAPE){
						
					} else if (event.key.keysym.sym == SDLK_ESCAPE){
						
					}*/
					break;
				case SDL_QUIT:
					exit = true;
					break;
					//break mainLoop;
				default:
					break;
			}
		}
}

void drawGLFrame(){
	glTranslatef(-2.5f, -1.5f, -5.0f);
	//glRotatef(xRotate, 1.0f, 0.0f, 0.0f);
	//glRotatef(yRotate, 0.0f, 1.0f, 0.0f);
	//glRotatef(zRotate, 0.0f, 0.0f, 1.0f);
	foreach (cube; cubes){
		cube.draw;
		cube.moveBy(0.01f, 0.01f, 0.0f);
	}
	xRotate += 0.1;
	yRotate += 0.1;
	zRotate += 0.1;
}